<?php
require_once('functions.php');

function getCars()
{
	$conn = getConnection();
	return $conn->query('SELECT * FROM Shopping_car');
}

function getDistintPurcase_ID()
{
	$conn = getConnection();
	return $conn->query('SELECT DISTINCT purchase_ID FROM Shopping_car');
}

function getCar($row)
{ 
		$conn = getConnection();
        $results = $conn->query("SELECT * FROM Shopping_car WHERE item_ID ='$row[item_ID]' AND purchase_ID='$row[purchase_ID]'");
        $row = $results->fetch_assoc();
        $conn->close();
        return $row;
}

function deleteShCart($id, $item_ID)
{
		$conn = getConnection();
		$conn->query("DELETE FROM Shopping_car WHERE purchase_ID = '$id' AND item_ID = '$item_ID'");
		$conn->close();
		header('Location: index.php');
}
		
function saveShCart($row)
{
        $conn = getConnection();
        $row2 = escapeRow($row, $conn);
        
        if (getCar($row2))
        	$sql =  "UPDATE Shopping_car SET purchase_ID='$row2[purchase_ID]', item_ID='$row2[item_ID]', quantity='$row2[quantity]' WHERE purchase_ID= '$row2[purchase_ID]' AND item_ID ='$row2[item_ID]' ";
        else
        	 $sql =  "INSERT INTO Shopping_car VALUES ('$row2[purchase_ID]', '$row2[item_ID]', '$row2[quantity]')";
        	 
        $results = $conn->query($sql);
        $error = $conn->error;
        $conn->close();
       
        return $error == '' ? true : array('SQL Error' => $error);
}

function blankShCart()
{
	return array('purchase_ID' => null, 'item_ID' => null, 'quantity' => null);
} 

